package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.product.api.domain.vo.CategoryVo;
import com.spzx.product.api.domain.Category;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-10-26
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> getCategoryTree(Long parentId) {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getParentId, parentId);
        //调用baseMapper中带条件查询的方法
        List<Category> categoryList = baseMapper.selectList(categoryLambdaQueryWrapper);
        //对categoryList中的子分类进行判断
        categoryList.forEach(category -> {
            //是否有父Id的值
            //其中注意设置判断条件出口
            Long count = baseMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, category.getId()));
            category.setHasChildren(count > 0 ? true : false);
        });
        return categoryList;
    }

    @Override
    public String importCategory(List<Category> categoryList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(categoryList) || categoryList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (Category category : categoryList) {
            try {
                // 验证是否存在这个用户
                Category c = baseMapper.selectById(category.getId());
                if (StringUtils.isNull(c)) {
                    category.setCreateBy(operName);
                    baseMapper.insert(category);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、类别 " + category.getName() + " 导入成功");
                } else if (updateSupport) {
                    category.setUpdateBy(operName);
                    baseMapper.updateById(category);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、类别 " + category.getName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、类别 " + category.getName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + category.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<Long> getCategoryList(Long categoryId) {
        ArrayList<Long> list = new ArrayList<>();
        List<Category> categoryList = this.getParentId(categoryId, new ArrayList<>());
        /*for (Category category :
                categoryList) {
            list.add(category.getParentId());
        }
        Collections.reverse(list);*/
        int size = categoryList.size();
        for (int i = size; i > 0; i--) {
            list.add(categoryList.get(i - 1).getId());
        }
        return list;
    }

    @Override
    public List<CategoryVo> getAllCategoryTree() {
        //调用自带的方法获取所有的分类信息
        List<Category> categoryList = baseMapper.selectList(null);
        //将所有的分类转换成CategoryVo类型
        List<CategoryVo> categoryVoList = categoryList.stream().map(category -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            return categoryVo;
        }).toList();
        //将所有的分类信息转换成分类树
        List<CategoryVo> categoryVoListTree = this.getCategoryVoTree(categoryVoList);
        return categoryVoListTree;
    }


    //CategoryVoList转换为分类树的方法
    private List<CategoryVo> getCategoryVoTree(List<CategoryVo> categoryVoList) {
        //创建一个返回的集合
        List<CategoryVo> categoryVoTree = new ArrayList<>();
        //遍历集合
        categoryVoList.forEach(categoryVo -> {
        //获取父ID等于0的分类信息
            if(categoryVo.getParentId() == 0){
                //给当前分类信息添加子分类
                categoryVo = this.addAndFindChildren(categoryVo,categoryVoList);
                //将当前分类信息添加到树的集合中
                categoryVoTree.add(categoryVo);
            }

        });
        return categoryVoTree;
    }


    //给分类添加子分类的方法
    private CategoryVo addAndFindChildren(CategoryVo categoryVo, List<CategoryVo> categoryVoList) {
        //遍历集合
        categoryVoList.forEach(categoryVo1 -> {
            //判断categoryvo1的父id是否为categoryvo的id值
            if (categoryVo1.getParentId() == categoryVo.getId()){
                //证明categoryvo1是categoryvo的子分类
                categoryVo1 = addAndFindChildren(categoryVo1,categoryVoList);
                //将categoryvo1添加到categoryvo的孩子中
                categoryVo.getChildren().add(categoryVo1);
            }
        });
        return categoryVo;
    }


    private List<Category> getParentId(Long categoryId, ArrayList<Category> categories) {
        while(categoryId > 0){
            LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
            categoryLambdaQueryWrapper.select(Category::getId,Category::getParentId)
                    .eq(Category::getId,categoryId);
            Category category = baseMapper.selectOne(categoryLambdaQueryWrapper);
            categories.add(category);
            return getParentId(category.getParentId(),categories);
        }
            return categories;
    }


}
